package com.sardine.base.http;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 北京京东世纪贸易有限公司<br>
 * Created with IntelliJ IDEA.
 * Date:2017/3/20
 * Time:15:40
 * MD5 加密工具
 * @author daifeng<br>
 *         daifeng@imdada.cn
 * @since JDK 1.7 <br>
 * Copyright (c) 2017 imdada System Incorporated All Rights Reserved.
 */
public class MD5Utils  {
    private static final Logger logger = LoggerFactory.getLogger(MD5Utils.class);

    /**
     * value为空字符串， 不参与加密
     * @param params
     * @param privateKey
     * @return
     */
    public static String getMd5Sign(Map<String, Object> params, String privateKey){
        List<String> list=new ArrayList<>();
        if(!CollectionUtils.isEmpty(params)){
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                if(entry.getValue()!=null && !StringUtils.isBlank(entry.getValue().toString())){
                    list.add(entry.getKey()+"="+entry.getValue());
                }
            }
            Collections.sort(list);
            String str= String.format("%s&key=%s", StringUtils.join(list, "&"), privateKey);
            return DigestUtils.md5Hex(str).toUpperCase();
        }
        return null;
    }
}
